package com.huangjue.backend.service.impl;

import com.huangjue.backend.dto.AiReport;
import com.huangjue.backend.dto.MultiAgentMessage;
import com.huangjue.backend.entity.AgentProcess;
import com.huangjue.backend.entity.AgentResult;
import com.huangjue.backend.mapper.AgentProcessMapper;
import com.huangjue.backend.mapper.AgentResultMapper;
import com.huangjue.backend.service.CallAgentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class CallAgentServiceImpl implements CallAgentService {

    private final AgentResultMapper agentResultMapper;
    private final AgentProcessMapper agentProcessMapper;
    private final String agentBaseApiUrl; // 配置项：Agent.baseApiUrl
    private final RestTemplate restTemplate;
    private final String apiUrl; // 配置项：MultiAgent.url

    public CallAgentServiceImpl(
            RestTemplate restTemplate,
            // 注入Mapper
            AgentProcessMapper agentProcessMapper,
            AgentResultMapper agentResultMapper,
            // 注入配置项：MultiAgent.url
            @Value("${MultiAgent.url}") String apiUrl,
            // 注入配置项：Agent.baseApiUrl
            @Value("${Agent.baseApiUrl}") String agentBaseApiUrl
    ) {
        this.restTemplate = restTemplate;
        this.agentProcessMapper = agentProcessMapper;
        this.agentResultMapper = agentResultMapper;
        this.apiUrl = apiUrl;
        this.agentBaseApiUrl = agentBaseApiUrl;
    }

    @Override
    public MultiAgentMessage callAgent(String msg,String studentId){
        // 1、构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 2、构建请求体
        Map<String, Object> request = new HashMap<>();
        request.put("code", msg);

        // 3、创建HttpEntity（包含请求头和请求体）
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

        try {
            // 4、发送请求并获取响应
            ResponseEntity<MultiAgentMessage> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.POST,
                    entity,
                    MultiAgentMessage.class
            );

            // 5、检查响应状态
            if (response.getStatusCode() == HttpStatus.OK) {
                MultiAgentMessage.AgentMessage[] messages = response.getBody().getMessages();
                AgentResult agentResult = new AgentResult();
                agentResult.setAgentResultId(response.getBody().getSession_id());
                agentResult.setResult(messages[4].getContent());
                agentResult.setStudentId(Integer.valueOf(studentId));
                agentResultMapper.insert(agentResult);
                AgentProcess agentProcess = new AgentProcess();
                for (int i=0;i<messages.length;i++) {
                    agentProcess.setAgentResultId(response.getBody().getSession_id());
                    agentProcess.setAgentProcess(messages[i].getContent());
                    agentProcess.setAgentType(messages[i].getRole());
                    agentProcessMapper.insert(agentProcess);
                }
                return response.getBody();
            } else {
                // 处理非200响应
                MultiAgentMessage errorResponse = new MultiAgentMessage();
                errorResponse.setStatus("error: API returned status: " + response.getStatusCode());
                return errorResponse;
            }
        } catch (Exception e) {
            // 处理异常
            MultiAgentMessage errorResponse = new MultiAgentMessage();
            errorResponse.setStatus("err:"+e.getMessage());
            return errorResponse;
        }

    }

    @Override
    public int getAiReport(String userID, String studentName, String startDate, String endDate){
        // 1、构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 2、构建请求体
        Map<String, Object> request = new HashMap<>();
        request.put("user_id", userID);
        request.put("student_name", studentName);
        request.put("start_date", startDate);
        request.put("end_date", endDate);

        // 3、创建HttpEntity（包含请求头和请求体）
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

        String generateReportApi = agentBaseApiUrl+"/v1/generate-report";

        //数据测试接口
        //String generateReportApi = AgentBaseApiUrl+"/v1/taskData";
        try {
            // 4、发送请求并获取响应
            ResponseEntity<AiReport> response = restTemplate.exchange(
                    generateReportApi,
                    HttpMethod.POST,
                    entity,
                    AiReport.class
            );

            if (response.getStatusCode() == HttpStatus.OK) {
                //返回结构正确后存入数据库
                AiReport aiReport = response.getBody();
                //生成结果的唯一编号-uuid
                UUID uuid = UUID.randomUUID();
                String uuidWithHyphens = uuid.toString();

                AgentResult agentResult = new AgentResult();
                agentResult.setAgentResultId(uuidWithHyphens);
                agentResult.setStudentId(Integer.valueOf(userID));
                agentResult.setResult(aiReport.getTaskResult());
                agentResultMapper.insert(agentResult);


                List<AgentProcess> agentProcessList = new ArrayList<>();
                List<AiReport.SubtasksInfo> subtasksInfos = aiReport.getSubtasksInfo();
                for (AiReport.SubtasksInfo subtasksInfo : subtasksInfos) {
                    AgentProcess agentProcess = new AgentProcess();
                    agentProcess.setAgentResultId(uuidWithHyphens);
                    agentProcess.setAgentType(subtasksInfo.getAgentRoleName());
                    agentProcess.setAgentProcess(subtasksInfo.getResult());
                    agentProcessList.add(agentProcess);
                }

                return agentProcessMapper.batchInsert(agentProcessList);
            }else {
                System.out.println(response);
                System.out.println("发送错误："+response.getStatusCode());
            }
            return 0;
         }catch (Exception e){
            //todo 智能体讨论失败处理
            System.out.println("错误:"+e.getMessage());
            return 0;
        }
    }
}